package com.hang.gymmanager.config;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpStatus;
import cn.hutool.json.JSONObject;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import com.hang.gymmanager.Enum.CommonConstant;
import com.hang.gymmanager.exception.BusinessException;
import com.hang.gymmanager.util.CacheTool;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

import static com.hang.gymmanager.Enum.CommonConstant.TOKEN_SIGN_KEY;

/**
 * @author wyq
 * @version v1.0.0
 * @explain
 * @date 2024/3/14 13:32
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class TokenInterceptor implements HandlerInterceptor {

    private final CacheTool cacheTool;

    @Override
    public boolean preHandle(HttpServletRequest request,HttpServletResponse response, Object handler) throws Exception {
        //验证请求头是否带token参数
        String token = request.getHeader(CommonConstant.GYM_HEADER);
        if(StrUtil.isEmpty(token)){
            log.error("请求头中不存在token");
            response.setStatus(HttpStatus.HTTP_UNAUTHORIZED);
            throw new BusinessException("请求头中不存在token");
//            return false;
        }
        //解析token并且判断token是不是过期
        if(!isValid(token)){
            log.error("校验token失败");
            response.setStatus(HttpStatus.HTTP_UNAUTHORIZED);
            throw new BusinessException("校验token失败");
            //return false;
        }
        return true;
    }


    /**
     * 检查token是否合法
     * @param token
     * @return
     */
    public boolean isValid(String token){
        JWT jwt;
        try {
            jwt = JWT.of(token);
        }catch (Exception e){
            log.error("解析token有误:{}",e.getMessage());
            return false;
        }
        if(!JWTUtil.verify(token, TOKEN_SIGN_KEY.getBytes())){
            log.error("token验签不通过");
            return false;
        }
        JSONObject payloads = jwt.getPayloads();
        Long expireTime = payloads.getLong("exp");
        Integer userId = payloads.getInt("userId");
//        if (DateUtil.currentSeconds() > expireTime) {
//            log.error("token已过期");
//            return false;
//        }
        if(!cacheTool.containsKey(CommonConstant.TOKEN_PREFIX+userId)){
            log.error("缓存中没有token");
            return false;
        }if(!StrUtil.equals(cacheTool.get(CommonConstant.TOKEN_PREFIX+userId),token)){
            log.error("非法token");
            return false;
        }
        return true;

    }

//    public static void main(String[] args) {
//        Map<String,Object> payloads  = new HashMap<>();
//        payloads.put("userId",1);
//        payloads.put("exp",1710835633);
//        String token = JWTUtil.createToken(payloads,TOKEN_SIGN_KEY.getBytes());
//        System.out.println(token);
//        isValid(token);
//    }


}
